const App = getApp()
const onHandToofg = require('../../utils/util');
const showT = require('../../utils/util');

Page({
  data: {
    rows: Array.from({ length: 10 }, (_, i) => i),//(_, i) => i 是一个箭头函数， _ 是一个占位符，表示不关心当前元素的值，i 是当前元素的索引
    cols: Array.from({ length: 10 }, (_, i) => i),
    seats: Array.from({ length: 100 }, () => 0),//0代表位置可用。1是选的座位，2是不可用座位
    availableseat: '/static/availableseat.png',
    selectseat: '/static/selectseat.png',
    unavailableseat: '/static/unavailableseat.png',
    selectedRows: [],
    selectedCols: [],
    btnname: '请先选座',
    btnUnselect: 'btn-unselect',
    btnselect: 'btn-select',
    currentBtn: 'btn-unselect',
    tf: true,
    seatInfo: [{
      id: '',
      cname: '',
      murl: '',
      seat: '',
      hall: '',
      price: 0,
      mname: '',
      day: '',
      time: '',
      state: '待使用',
      num:0
    }],
    cid: 0,
    mid: 0,
    unavailableIndexes: [],
    singleprice: 0,
    Token:''
  },
  
  onLoad() {
    const userToken = wx.getStorageSync('userToken'); 
    this.setData({
      Token:userToken
    });
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on('acceptDataFromBookingPage', (data) => {
      this.setData({
        'seatInfo[0].time': data.starttime,
        cid: data.cid,
        mid: data.mid,
        'seatInfo[0].day': data.day,
        'seatInfo[0].hall': data.tickets.hall,
        singleprice: data.tickets.price
      });

      const requestData = {
        cid: this.data.cid,
        mid: this.data.mid,
        starttime: this.data.seatInfo[0].time
      };
      //获取已选座位信息
      wx.request({
        url: App.globalData.backend_add+"api/bookings/getSeat",
        method: 'POST',
        data: JSON.stringify(requestData),
        header: {
          'Authorization': this.data.Token,
          'content-type': 'application/json'
        },
        success: (res) => {
          console.log('请求成功：', res.data.msg+" "+res.data.code);  
          this.setData({
            unavailableIndexes: res.data.data
          });
          this.initUnavailableSeats(this.data.unavailableIndexes);
        },
        fail: (err) => {
          console.error('请求失败：', err);
        }
      });

      const index = this.data.mid;
      //根据传入的电影id获取电影信息
      wx.request({
        url: App.globalData.backend_add + 'api/getMovieByMid?id=' + index,
        method: 'POST',
        header: {
          'Authorization': this.data.Token,
          'content-type': 'application/json'
        },
        success: (res) => {
          wx.hideLoading();
          console.log('请求成功：', res.data.msg+" "+res.data.code);  
          this.setData({
            "seatInfo[0].mname": res.data.data[0].name,
            "seatInfo[0].murl": res.data.data[0].movieImageUrl
          });
        },
        fail: (err) => {
          wx.hideLoading();
          showT.showT();
          /* wx.showToast({
            title: '加载失败，请稍后再试',
            icon: 'none',
            duration: 2000
          }); */
        }
      });

      const index1 = this.data.cid;
      //根据传入影院id获取影院信息
      wx.request({
        url: App.globalData.backend_add + 'api/getCinemaByCid?id=' + index1,
        method: 'POST',
        header: {
          'Authorization': this.data.Token,
          'content-type': 'application/json'
        },
        success: (res) => {
          wx.hideLoading();
          console.log('请求成功：', res.data.msg+" "+res.data.code);  
          this.setData({
            "seatInfo[0].cname": res.data.data[0].name
          });
        },
        fail: (err) => {
          wx.hideLoading();
          showT.showT();
          /* wx.showToast({
            title: '加载失败，请稍后再试',
            icon: 'none',
            duration: 2000
          }); */
        }
      });
    });
  },
  //初始化已选座位
  initUnavailableSeats(unavailableIndexes) {
    const newSeats = this.data.seats.slice();//创建座位数组的一个副本。slice() 方法用于创建数组的浅拷贝，这样原始座位数组不会直接被修改
    unavailableIndexes.forEach(seatData => {
      newSeats[seatData.seat] = 2; // 设置座位状态为不可用
    });
    this.setData({
      seats: newSeats
    });
  },

  //选择座位
  selectSeats(event) {
    const index = event.currentTarget.dataset.index;//当用户点击座位，记录索引
    const seatStatus = this.data.seats[index];
    if (seatStatus === 0 || seatStatus === 1) {
      const newSeats = this.data.seats.slice();
      const row = Math.floor(index / this.data.cols.length);
      const col = index % this.data.cols.length;//一维数组计算二维数组的位置
      newSeats[index] = seatStatus === 0 ? 1 : 0;
      let updated = false;
      if (seatStatus === 0) {
        this.data.selectedRows.push(row + 1);
        this.data.selectedCols.push(col + 1);
        updated = true;
      } else {
        const rowIndex = this.data.selectedRows.indexOf(row + 1);
        const colIndex = this.data.selectedCols.indexOf(col + 1);
        this.data.selectedRows.splice(rowIndex, 1);
        this.data.selectedCols.splice(colIndex, 1);
        updated = true;
      }
      const totalSeatsSelected = this.data.selectedRows.length;
      this.data.seatInfo[0].price = parseFloat(totalSeatsSelected * this.data.singleprice).toFixed(2);
      const btnText = totalSeatsSelected > 0 ? `￥${this.data.seatInfo[0].price} 确认选座` : '请先选座';
      
      // 拼接座位信息
      const seatInfo = this.data.selectedRows.map((row, i) => `${row}行${this.data.selectedCols[i]}列`).join(' ');//.map创建新数组

      this.setData({
        seats: newSeats,
        selectedRows: this.data.selectedRows,
        selectedCols: this.data.selectedCols,
        tf: this.data.selectedRows.length > 0 ? false : true,
        currentBtn: this.data.selectedRows.length > 0 ? 'btn-select' : 'btn-unselect',
        btnname: btnText,
        'seatInfo[0].seat': seatInfo
      }, () => {
        if (updated) {
          console.log("当前选中的行:", this.data.selectedRows);
          console.log("当前选中的列:", this.data.selectedCols);
          console.log("拼接后的座位信息:", this.data.seatInfo[0].seat);
        }
      });
    }
  },
  //提交座位信息给后端
  submitSeats() {
    const selectedIndexes = this.data.selectedRows.map((row, i) => (row - 1) * this.data.cols.length + (this.data.selectedCols[i] - 1));
    const requestData = {
      cid: this.data.cid,
      mid: this.data.mid,
      starttime: this.data.seatInfo[0].time,
      seats: selectedIndexes
    };
    
    wx.request({
      url: App.globalData.backend_add+"api/bookings/insertSeats",
      method: 'POST',
      data: JSON.stringify(requestData),
      header: {
        'Authorization': this.data.Token,
        'content-type': 'application/json'
      },
      success: (res) => {
        console.log('请求成功：', res.data.msg+" "+res.data.code);  
        this.setData({
          unavailableIndexes: res.data.data
        });
      },
      fail: (err) => {
        console.error('请求失败：', err);
      }
    });

    const newSeats = this.data.seats.map(seat => seat === 1 ? 2 : seat);
    this.setData({
      seats: newSeats,
      "seatInfo[0].num":this.data.selectedRows.length,
      selectedRows: [],
      selectedCols: []
    }, () => {
      wx.showLoading({
        title: '位置信息提交中',
      });
      this.setData({
        currentBtn: 'btn-unselect',
        btnname: '请先选座',
      });
      
      setTimeout(function () {
        wx.hideLoading()
        const Data = this.data.seatInfo[0]
        //提交订单信息给后端
        wx.request({
          url: App.globalData.backend_add+"api/bookings/insertOrder",
          method: 'POST',
          data: (Data),
          header: {
            'Authorization': this.data.Token,
            'content-type': 'application/json'
          },
          success: (res) => {
            console.log('请求成功：', res.data.msg+" "+res.data.code);  
          },
          fail: (err) => {
            console.error('请求失败：', err);
          }
        });
        onHandToofg.onHandToofg()
      }.bind(this), 2000);
    });
  },
});